<?php


namespace app\api\service\activity_order;

use app\api\model\SjActivity;
use app\api\model\SjActivityOrder;
use app\api\model\SjActivityOrderItem;
use app\api\model\User;
use app\api\service\Token;
use think\Db;
use think\Exception;
use think\facade\Log;

class SjActivitySer extends Token
{
    /**
     * 订单信息
     */
    protected $order;

    /**
     * 用户信息
     */
    protected $user;

    /**
     * 活动信息
     */
    protected $sjActivity;

    /**
     * 入口方法
     */
    public function entrance($order)
    {
        Log::init([
            'type' => 'File'
        ]);
        $this->order = $order;
        $this->user = User::where('openid',$this->order['openid'])->find();
        $this->sjActivity = SjActivity::get($this->order['activity_id']);
        return $this->updateOrder();
    }

    /**
     *  更新订单
     */
    protected function updateOrder()
    {
        Db::startTrans();
        try {
            SjActivityOrder::where('id',$this->order['id'])
                ->update([
                    'status' => 2,
                    'pay_time' => time()
                ]);
            SjActivityOrderItem::where('order_id',$this->order['id'])->update([
                'status' => 2
            ]);
            $this->createCodeImg();
            Db::commit();
            return true;
        }
        catch (Exception $e){
            Db::rollback();
            Log::write('官方活动订单回调:'.$e,'error');
            return false;
        }
    }


    /**
     * 生成二维码
     */
    protected function createCodeImg()
    {
        // 生成订单二维码
        $token = new Token();
        $list = SjActivityOrderItem::where('order_id',$this->order['id'])
            ->select()->toArray();
        foreach ($list as &$v){
            $token->setCode('sj',$v['id']);
        }
    }
}